package com.runningrookie.service.impl;

import com.runningrookie.domain.ConcurrencyLockBean;
import com.runningrookie.mapper.ConcurrencyLockMapper;
import com.runningrookie.service.ConcurrencyLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
public class ConcurrencyLockServiceImpl implements ConcurrencyLockService {
    ConcurrencyLockMapper mapper;

    @Autowired
    ConcurrencyLockServiceImpl(ConcurrencyLockMapper mapper) {
        this.mapper = mapper;
    }

    @Override
    public Boolean tryLock(String businessNode, String businessUniqueNo) {
        long threadId = Thread.currentThread().getId();
        ConcurrencyLockBean concurrencyLockBean = mapper.selectConcurrencyLock(businessNode, businessUniqueNo);
        if (concurrencyLockBean != null) {
            log.info("{}数据正在操作中，请稍后", threadId);
            return false;
        }

        ConcurrencyLockBean lock = new ConcurrencyLockBean();
        lock.setBusinessNode(businessNode);
        lock.setBusinessUniqueNo(businessUniqueNo);
        lock.setThreadId(threadId);
        try {
            int insertCount = mapper.insertConcurrencyLock(lock);
            if (insertCount == 0) {
                log.info("{}获取锁失败，请稍后重试", threadId);
                return false;
            }
        } catch (Exception e) {
            log.info("{}获取锁异常，请稍后重试", threadId);
            return false;
        }
        log.info("{}完成锁表插入", threadId);
        return true;
    }

    @Override
    public void unLock(String businessNode, String businessUniqueNo) {
        ConcurrencyLockBean lock = new ConcurrencyLockBean();
        long threadId = Thread.currentThread().getId();
        lock.setThreadId(threadId);
        lock.setBusinessNode(businessNode);
        lock.setBusinessUniqueNo(businessUniqueNo);
        mapper.deleteConcurrencyLock(lock);
        log.info("{}执行解锁完毕", threadId);
    }
}
